package com.m.pojo;

import com.m.Range;

import java.lang.reflect.Field;

public class AnnoPerson {
    @Range
    public String name;
    @Range
    public Integer id;

    public void check(AnnoPerson p) throws IllegalAccessException {
        //遍历字段
        for (Field field : p.getClass().getFields()) {
            //如果字段中含有range注解
            if (field.isAnnotationPresent(Range.class)) {
                //获取field
                Object object = field.get(p);
                //判断field类型
                if (object instanceof String s) {
                    //判断值是否满足range范围
                    Range range = field.getAnnotation(Range.class);
                    if (s.length() < range.min() || s.length() > range.max()) {
                        throw new IllegalArgumentException("Invalid field: " + field.getName());
                    }
                }
                if (object instanceof Integer i) {
                    //判断值是否满足range范围
                    Range range = field.getAnnotation(Range.class);
                    if (i < range.min() || i > range.max()) {
                        throw new IllegalArgumentException("Invalid field: " + field.getName());
                    }
                }
            }
        }
    }

    public AnnoPerson() {
    }

    public AnnoPerson(String name, Integer id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}
